package 面试代码;

/**
 * @author zx
 * @create 2023-03-23 12:31
 */
public class 三个线程交替打印100 {
    private int num = 0;
    private static Object lock = new Object();
    public static void main(String[] args) {
        三个线程交替打印100 t = new 三个线程交替打印100();
        Thread t1 = new Thread(){
            @Override
            public void run() {
                t.print(0);
            }
        };
        Thread t2 = new Thread(){
            @Override
            public void run() {
                t.print(1);
            }
        };
        Thread t3 = new Thread(){
            @Override
            public void run() {
                t.print(2);
            }
        };
        t1.start();
        t2.start();
        t3.start();
    }
    private void print(int curThread) {
        while (true) {
            synchronized (lock) {
                while (!(num % 3 == curThread)) {
                    if(num >= 100){
                        break;
                    }
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                if(num >= 100){
                    break;
                }
                num++;
                System.out.println(Thread.currentThread().getName() + ": " + num);
                lock.notifyAll();
            }
        }
    }
}
